import type { ClassData, StudentList } from './interface'
import type { ExamResultEnum } from './enum'
import styles from './index.module.less'
import FoldBox from '@/components/Common/FoldBox'
import NavBar from '@/components/Global/NavBar'
import classNames from 'classnames'
import { Divider, Empty, InfiniteScroll } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { history } from 'umi'
import { fetchStudentList } from '../api'
import { SkeletonParagraphWrap, SkeletonTitleWrap } from '@/components/Common/Skeleton'
import { useFetchPageList } from '@/hooks/useFetchPageList'
import MoreLoader from '@/components/Common/MoreLoader'
import Tag from '@/components/Common/Tag'
import { hideIDCardInfo } from '@/utils/textHelper'
import { GROUP_TYPE, YesNo } from '@/constant/enum'
import { GroupArray, JoinItem } from '@/utils/array'
import { ExamResult, AssessType } from './enum'

export const StudentManage = () => {
    const historyQuery = history.location.query as { id: string }

    const id = Number(historyQuery.id)

    const [loading, setLoading] = useState<boolean>(false)
    const [classInfo, setClassInfo] = useState<ClassData>()

    /** 是否为网创班级 */
    const isInternetBusiness = classInfo?.configure.group_type === GROUP_TYPE.InternetBusiness
    /** 是否提交成绩 */
    const hasScore = classInfo?.configure.is_score === YesNo.Yes

    const { dataList, hasMore, loading: listLoading, loadMore } = useFetchPageList<StudentList>(
        `/country/group/student/${id}`,
    )

    /**
     * 成绩视图
     * 可以用Table的形式展示来替换此组件
     * UI: https://lanhuapp.com/web/#/item/project/stage?tid=887e9263-790d-42fe-9cb0-de1fa077b318&pid=488d86fb-4366-4875-acbc-85e0fdfc785a
     */
    const ScoreGridView = ({
        trial_score,
        written_score,
        attendance_score,
        gain_score,
        plan_score,
        complex_score,
    }: {
        trial_score: number | string
        written_score: number | string
        attendance_score: number
        gain_score: number | string
        plan_score: number | string
        complex_score: ExamResultEnum
    }) => {
        const ScoreItems: { title: string; value: string | number; visible: boolean }[] = [
            {
                title: '试讲',
                value: trial_score ?? '-',
                visible: [AssessType.UnSelect, AssessType.WriteAndLecture, AssessType.Lecture].some(
                    it => it === classInfo?.configure.assess_type,
                ),
            },
            {
                title: '笔试',
                value: written_score ?? '-',
                visible: [AssessType.UnSelect, AssessType.WriteAndLecture, AssessType.Write].some(
                    it => it === classInfo?.configure.assess_type,
                ),
            },
            { title: '缺勤天数', value: `${attendance_score}天`, visible: true },
            {
                title: '综合评价',
                value: ExamResult[complex_score] ?? '-',
                visible: classInfo?.configure.assess_type === AssessType.None,
            },
            { title: '成果', value: gain_score ?? '-', visible: isInternetBusiness },
            { title: '规划书', value: plan_score ?? '-', visible: isInternetBusiness },
        ].filter(it => it.visible)

        // 根据UI图, 展示数据项大于4个时多行展示
        const isMultiRow = ScoreItems.length > 4
        // 多行展示时每行的展示数量
        const multiRowColumnCount = 3
        // 根据UI图, 展示数据项大于4个时一行展示三个
        const columnCount = isMultiRow ? multiRowColumnCount : ScoreItems.length

        // 添加空白数据项, 使得在多行情况下每一行元素数量一致
        if (isMultiRow && ScoreItems.length % 3 !== 0) {
            const lackCount = columnCount - (ScoreItems.length % columnCount)
            ScoreItems.push(
                ...(new Array(lackCount).fill({
                    title: '',
                    value: '',
                    visible: true,
                }) as typeof ScoreItems),
            )
        }

        const ScoreItemsForRender = ScoreItems.map(it => (
            <div
                key={it.title}
                className={styles.expandStudentInfo_detail_item}
                style={{
                    // 1px(分割线宽度)
                    width: `calc(${100 / columnCount}% - 1px)`,
                }}
            >
                <div>{it.title}</div>
                <div>{it.value}</div>
            </div>
        ))

        // 将元素分行, 并添加横向分割线
        const GroupScoreItemsForRender = JoinItem(GroupArray(ScoreItemsForRender, columnCount), [
            <Divider
                key="group-divider"
                style={{ width: '100%', height: '1px', margin: '10px 0' }}
            />,
        ])

        return (
            <div
                className={styles.expandStudentInfo_detail}
                style={{
                    justifyContent: isMultiRow ? 'flex-start' : 'space-between',
                }}
            >
                {GroupScoreItemsForRender.map((it, index) =>
                    JoinItem(
                        it,
                        <Divider
                            key={`divider-${index}`}
                            direction="vertical"
                            style={{ height: '2em', margin: 0 }}
                        />,
                    ).map(dom => dom),
                )}
            </div>
        )
    }

    useEffect(() => {
        const initData = async () => {
            try {
                setLoading(true)
                const { data } = await fetchStudentList(id)
                setClassInfo(data)
            } finally {
                setLoading(false)
            }
        }
        initData()
    }, [id])

    return (
        <div>
            <NavBar title={'学员管理'} />
            <div className={styles.page}>
                <SkeletonTitleWrap loading={loading} animated>
                    <div className={styles.className}>
                        {`${classInfo?.configure.name || '-'} ${classInfo?.configure.code || '-'}`}
                    </div>
                </SkeletonTitleWrap>

                <div className={styles.summary}>
                    <div className={styles.summary_count}>
                        <div>班级人数</div>
                        <div>{classInfo?.total}</div>
                    </div>
                    <div className={styles.summary_passCount}>
                        <div>合格人数</div>
                        <div>{hasScore ? classInfo?.assess_results : 0}</div>
                    </div>
                    <div className={styles.summary_passRate}>
                        <div>合格率</div>
                        <div>
                            {hasScore
                                ? `${parseFloat(String(classInfo?.pass_rate || 0)).toFixed(2)}%`
                                : '0%'}
                        </div>
                    </div>
                </div>

                <SkeletonParagraphWrap
                    animated
                    lineCount={5}
                    loading={dataList.length === 0 && listLoading}
                >
                    {dataList.length > 0 && (
                        <FoldBox.Group>
                            <div className={styles.list}>
                                {dataList.map(dataItem => {
                                    const { idcard, realname, username, is_qualified } = dataItem

                                    return (
                                        <FoldBox
                                            key={idcard}
                                            value={idcard}
                                            title={realname}
                                            statusBar={(() => {
                                                if (is_qualified === '') return <></>

                                                return is_qualified === '合格' ? (
                                                    <Tag color="success" name="合格" />
                                                ) : (
                                                    <Tag color="error" name="不合格" />
                                                )
                                            })()}
                                            expandContent={
                                                <div className={styles.expandStudentInfo}>
                                                    {/* 成绩展示 */}
                                                    <ScoreGridView {...dataItem} />

                                                    <div
                                                        className={styles.expandStudentInfo_result}
                                                    >
                                                        考核结果：
                                                        <span
                                                            className={classNames({
                                                                [styles.expandStudentInfo_result_pass]:
                                                                    is_qualified &&
                                                                    is_qualified === '合格',
                                                                [styles.expandStudentInfo_result_unPass]:
                                                                    is_qualified &&
                                                                    is_qualified !== '合格',
                                                            })}
                                                        >
                                                            {is_qualified || '-'}
                                                        </span>
                                                    </div>
                                                </div>
                                            }
                                        >
                                            <div className={styles.studentInfo}>
                                                <div>账号：{username || '-'}</div>
                                                <div>身份证：{hideIDCardInfo(idcard) || '-'}</div>
                                            </div>
                                        </FoldBox>
                                    )
                                })}
                            </div>

                            <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                                <MoreLoader hasMore={hasMore} />
                            </InfiniteScroll>
                        </FoldBox.Group>
                    )}

                    {dataList.length === 0 && <Empty description="暂无数据" />}
                </SkeletonParagraphWrap>
            </div>
        </div>
    )
}

export default StudentManage
